package com.adouteam.simple.wechat.service;

import com.adouteam.simple.wechat.base.Constant;
import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.base.WeixinUrls;
import com.adouteam.simple.wechat.bean.AccessToken;
import com.adouteam.simple.wechat.tool.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * 令牌服务
 *
 * @author buxianglong
 */
public class AccessTokenService{
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenService.class);

    private WechatConstants wechatConstants;

    public AccessTokenService(WechatConstants wechatConstants){
        this.wechatConstants = wechatConstants;
    }

    /**
     * 获取缓存的AccessToken值
     *
     * @return AccessToken令牌
     */
    public String getAccessToken(){
        return getAccessTokenFromWeiXin();
    }

    /**
     * 直接向微信，请求AccessToken
     *
     * @return AccessToken令牌
     */
    protected String getAccessTokenFromWeiXin(){
        String url = WeixinUrls.replace(WeixinUrls.ACCESS_TOKEN, wechatConstants, null);
        return HttpUtil.get(url, null, (httpResponse) -> {
            String responseContent = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("utf-8"));
            if(StringUtils.isBlank(responseContent)){
                return null;
            }
            logger.debug(Constant.LOGGER_PREFIX + "responseContent: " + responseContent);
            AccessToken newAccessToken = JSONObject.parseObject(responseContent, AccessToken.class);
            if(null == newAccessToken || StringUtils.isBlank(newAccessToken.getAccessToken())){
                return null;
            }
            return newAccessToken.getAccessToken();
        });
    }
}
